package com.awenhui.demo.core.handler;

import com.awenhui.demo.core.base.IBaseEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * @author yuxf
 * @version 1.0
 * @date 2021/2/7 14:19
 */
@MappedJdbcTypes(JdbcType.INTEGER)
public class ResultCodeTypeHandler extends BaseTypeHandler<IBaseEnum> {

//    private final Class<IBaseEnum> type;
//    private final IBaseEnum[] enums;
//
//    public ResultCodeTypeHandler(Class<IBaseEnum> type) {
//        this.type = type;
//        this.enums = type.getEnumConstants();
//    }


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, IBaseEnum parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getValue());
    }

    @Override
    public IBaseEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int value = rs.getInt(columnName);
        return getResultCodeEnum(value);
    }

    @Override
    public IBaseEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int value = rs.getInt(columnIndex);
        return getResultCodeEnum(value);
    }

    @Override
    public IBaseEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int value = cs.getInt(columnIndex);
        return getResultCodeEnum(value);
    }

    private IBaseEnum getResultCodeEnum(int value) {
        return null;// Arrays.stream(enums).filter(r -> r.getValue() == value).findFirst().orElse(null);
    }
}
